<?php
            
use app\model\Comm; 
use app\model\Theme; 
use app\model\Worker; 
use app\model\Userdata; 


/**
 * Author: cbw
 * Desc: 红包雨
 * Time: 2022/1/14 9:37 上午
 * Email: 17854288794@163.com
 */
class Index_Page extends PluginMobilePage {

    function main()
    {
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        if ($fromtype!='wxapp') {
            return_json(1,'非法请求');
        }
        $themeid = isset($_P['themeid'])?$_P['themeid']:'';
        $fromuid = (isset($_P['fromuid']) && $_P['fromuid'])?intval($_P['fromuid']):0;
        $workerid = isset($_P['workerid'])?$_P['workerid']:'';
        $theme = Theme::getThemeById($themeid);
        if (!$themeid || !$theme['id']) {
            return_json(1,'活动入口不正确');
        }
        //基本检测
        $fans = $this->checkuser();
        $error = RedRainModel::checkBaseError($theme);
        $res = RedRainModel::getBaseInfo($themeid,$fans,$_C,$fromuid,$_S);
        $res['error']=$error;
        $res['redrain_mode']=$_S['redrain'];//当前模式
        $res['fans_authorized'] = false;
        if ($fans['nickname'] && ($fans['avatar'] && $fans['avatar']!='https://css2020.yixuan.net/2020css/yx2020/images/question.png')){
            $res['fans_authorized'] = true;
        }
        $format_res = $res;
        return_json(0,'',$format_res);
    }

    /**
     * Desc:我的红包
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 6:09 下午
     */
    function mine()
    {
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        if ($fromtype!='wxapp') {
            return_json(1,'非法请求');
            exit();
        }
        $themeid = isset($_P['themeid'])?$_P['themeid']:'';
        $fromuid = isset($_P['fromuid'])?$_P['fromuid']:'';
        $workerid = isset($_P['workerid'])?$_P['workerid']:'';
        $theme = Theme::getThemeById($themeid);

        if (!$themeid || !$theme['id']) {
            return_json(1,'活动入口不正确');
            exit();
        }
        //基本检测
        $fans = $this->checkuser();
        //获我的最高可用的红包记录
        $my_redrain_base_info = RedRainModel::getUserCanUseRedRainFlag($themeid,$fans['uid'],$_C,$_S);
        //助力记录
        $my_friend_info = RedRainModel::getUserFriendInfo($themeid,$fans,$_C);
        //红包记录
        $my_redrain_flag =RedRainModel::getFrontUserRedRainList($themeid,$fans['uid'],$_C,$_S);
        //机会记录
        $my_chance_flag = RedRainModel::getFrontUserChanceList($themeid,$fans['uid']);
        $rules = $_C['redrain_rules'];
        //判断用户是否已经体现
        //$redrain_used = RedRainModel::getFlagTotal($fans['uid'],$themeid,1);
        //活动规则
        //员工信息
        if ($workerid && $workerid!='null'){
            $isworker = Worker::getThemeWorkerByUid($workerid,$themeid,1);
        }else{
            $isworker = Worker::getThemeWorkerByUid($fans['workerid'],$themeid,1);
        }
        $worker_info = [
            'name'=>$isworker['username'],
            'qrcode'=>$isworker['qrcode'],
            'avatar'=>$isworker['avatar'],
            'mobile'=>$isworker['mobile'],
        ];
        $company_mobile = $theme['mobile'];
        //用户日志收集
        Userdata::addLog($themeid, $fans['uid'], 28);
        $format_res = [
            'my_redrain_base_info'=>$my_redrain_base_info,
            'my_friend_info'=>$my_friend_info,
            'my_redrain_flag'=>$my_redrain_flag,
            'my_chance_flag'=>$my_chance_flag,
            'rules'=>$rules,
           // 'redrain_used'=>$redrain_used,
            'redrain_mode'=>$_S['redrain'],
            'redrain_get_type'=>$_C['redrain_get_type'],
            'worker_info'=>$worker_info,
            'company_mobile'=>$company_mobile,
        ];
        return_json(0,'',$format_res);
    }

    /**
     * Desc:好友助力
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 3:29 下午
     */
    function friendHelp()
    {
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        if ($fromtype=='wxapp'){
            $themeid = isset($_P['themeid'])?$_P['themeid']:'';
            $fromuid = isset($_P['fromuid'])?$_P['fromuid']:'';
            $workerid = isset($_P['workerid'])?$_P['workerid']:'';
            $themeid = isset($_P['themeid'])?$_P['themeid']:'';
            $theme = Theme::getThemeById($themeid);

            if (!$themeid || !$theme['id']) {
                return_json(1,'活动入口不正确');
            } else {
                //基本检测
                $fans = $this->checkuser();
                if ($_C['redrain_friend_view_num']>0 && $_C['redrain_friend_view_limit']>0){
                    $from_fans = RedRainModel::getFansInfoByWhere(['themeid'=>$themeid,'uid'=>$fromuid]);
                    $friend_help_flag_total = RedRainModel::getFriendHelpFlagTotal($themeid,$from_fans['uid'],$fans['uid']);
                    if ($friend_help_flag_total<1){
                        //当前好友没有助力过
                        $res = RedRainModel::apiInsertChance($themeid,$_C,$from_fans,2,$fans['uid']);
                        if ($res){
                            return_json(0,'助力成功',[]);
                        }else{
                            return_json(1,'助力失败',[]);
                        }
                    }else{
                        return_json(1,'您已经助力过',[]);
                    }
                }else{
                    return_json(1,'好友助力已关闭',[]);
                }
            }
        }else{
            return_json(1,'非法请求');
        }
    }

    /**
     * Desc:生成红包雨数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/15 2:16 下午
     */
    function buildRedRain()
    {
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        if ($fromtype!='wxapp') {
            return_json(1,'非法请求');
            exit();
        }
        $themeid = isset($_P['themeid'])?$_P['themeid']:'';
        $fromuid = isset($_P['fromuid'])?$_P['fromuid']:'';
        $workerid = isset($_P['workerid'])?$_P['workerid']:'';
        $theme = Theme::getThemeById($themeid);
        if (!$themeid || !$theme['id']) {
            return_json(1,'活动入口不正确');
            exit();
        }

        $baseError = RedRainModel::checkBaseError($theme);
        if($baseError){
            return_json(1,$baseError['msg']);
            exit();
        }

        $fans = $this->checkuser();
        //根据IP检测地区
        if (!empty($_C['redrain_city'])) {
            if ($_C['redrain_locationtype'] == 1) {
                $GLat = $_P['GLat'];
                $GLng = $_P['GLng'];
                $City = Comm::getCityDW($GLat, $GLng, $_C['redrain_city']);
            } else {
                $ClientIp = $_G['clientip'];
               //$City = Comm::getCity($system, $ClientIp, $config['comm4city']);
                try{
                    $City = Comm::getCity($_S, $ClientIp,$_C['redrain_city']);
                }catch (Exception $e){
                    return_json(1,'您不在活动地区');
                }
            }
            if($City['status'] == 0){
                return_json(1,'您不在活动地区');
            }
        }

        //通用验证
        $check_res = RedRainModel::redrainBaseCheck($themeid,$fans,$_C);
        if($check_res['code']>0){
            return_json(1,$check_res['msg']);
        }

        if($fans['jihui'] < 1){
            return_json(1,'您已经没有抽奖机会了');
        }
        $all_total = $_C['redrain_once_amount']*130;
        $num=140;
        $min= 0.01*100;
        $max= $all_total-($min*$num)>$min?$all_total-($min*$num):$min+1;
        //炸弹和金币出现开始 15%到20% 位置
        $gold_start_num = ceil($num*mt_rand(15,20)/100);
        //平均值
        $redrain_vag =  round($all_total/$num,2);
        //最大值 游戏中大于等于最大值  游戏结束  上报数据
        $max_total = $all_total-(mt_rand(2,5)*ceil($redrain_vag));

        //终止判断红包金额
        $stop_total = $_C['redrain_once_amount']*100;
        //炸弹个数
        $bomb_num = 10;
        //game_time 游戏时长 秒
        $game_time = 30;
        if ($_S['redrain']>2){
            $bomb_num = 20;
            $game_time = 20;
        }
        //炸弹出现阶梯
        $bomb_ladder = floor(($num-$gold_start_num-1)/$bomb_num);
        //炸弹的金额
        $start_ladder = $gold_start_num;
        $bomb_array = array();
        for ($i=1;$i<=$bomb_num;$i++){
            $key = mt_rand($start_ladder+$bomb_ladder*($i-1)+1,$start_ladder+$bomb_ladder*$i);
            $bomb_amount =  round($redrain_vag*mt_rand(1.8*10,3.5*10)/1000*-1,2);
            $bomb_array[$key] = $bomb_amount*100;
        }
        $total=$all_total;
        $res=array();
        for ($ii=1;$ii<=$num;$ii++){
            if($ii<$num){
                $vag=round($total/($num-$ii+1),2);
                //保证剩下红包金额不小于范围中的最小值
                $tmp_max=min($max,round($total-($num-$ii+1)*$min,2));
                //保证剩下红包金额不大于范围中的最大值
                $tmp_min=max($min,round($total-($num-$ii+1)*$max,2));
                $vag_diff=min($tmp_max-$vag,$vag-$tmp_min);//这是波动幅度
                $end_max=$vag+$vag_diff;
                $end_min=$vag-$vag_diff;
                if ($end_max<$end_min){
                    $amount=mt_rand($end_max,$end_min);
                }else{
                    $amount=mt_rand($end_min,$end_max);
                }

                $total-=$amount;
                //添加炸弹
                if($amount>=$redrain_vag&&$ii>=$gold_start_num&&mt_rand(1,100)<65){
                    //金币 大于平均值的65%的概率成为金币
                    $res[]= array('type' => 'gold','amount' => $amount);   ;
                }else{
                    $res[]= array('type' => 'redpacket','amount' => $amount);   ;
                }
            }else{   //最后一个
                $res[]= array('type' => 'redpacket','amount' => $total);   ;
                $total = 0;
            }
            if(isset($bomb_array[$ii])){
                $res[] =  array('type' => 'bomb','amount' => $bomb_array[$ii]);
            }
        }
        $gold_num = 0;
        $redpacket_num = 0;
        $gold_amount = 0;
        $redpacket_amount = 0;
        $bomb_num = 0;
        $bomb_amount = 0;

        $redpacket_arr = [];
        $gold_arr = [];
        $bomb_arr = [];
        foreach ($res as  $v){
            if($v['type'] == 'gold'){
                $gold_num++;
                $gold_amount +=$v['amount'];
                array_push($gold_arr,$v);
            }
            if($v['type'] == 'redpacket'){
                $redpacket_num++;
                $redpacket_amount +=$v['amount'];
                array_push($redpacket_arr,$v);
            }
            if($v['type'] == 'bomb'){
                $bomb_num++;
                $bomb_amount +=$v['amount'];
                array_push($bomb_arr,$v);
            }
        }
        $rand_temp_arr = RedRainModel::makeRandTempArr();
        $res = [
            'redpacket_arr'=>$redpacket_arr,
            'gold_arr'=>$gold_arr,
            'bomb_arr'=>$bomb_arr,
            'rand_temp_arr'=>$rand_temp_arr
        ];
        //用户日志收集
        Userdata::addLog($themeid, $fans['uid'], 26, '');

        //红包雨下落模式
        $redrain_speed  = $_C['redrain_speed'];
        $redrain_drop_mode  = $_C['redrain_drop_mode'];
        $format_res = [
            'list'=>$res,'redrain_mode'=>$_S['redrain'],'max_total'=>$stop_total,
            'game_time'=>$game_time,'redrain_vag'=>ceil($redrain_vag),
            'redrain_speed' => $redrain_speed,//下落速度 5-10
            'redrain_drop_mode' => $redrain_drop_mode,//下落模式  0 密集 1稀松
        ];
        return_json(0,'',$format_res);

    }

    /**
     * Desc:提交获取红包金额
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 8:34 下午
     */
    function commun()
    {
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        if ($fromtype=='wxapp'){
            $themeid = isset($_P['themeid'])?$_P['themeid']:'';
            $fromuid = isset($_P['fromuid'])?$_P['fromuid']:'';
            $workerid = isset($_P['workerid'])?$_P['workerid']:'';
            $themeid = isset($_P['themeid'])?$_P['themeid']:'';
            $amount = isset($_P['amount'])?$_P['amount']:0;
            $theme = Theme::getThemeById($themeid);

            if (!$themeid || !$theme['id']) {
                return_json(1,'活动入口不正确');
            } else {
                //基本检测
                $fans = $this->checkuser();
                if($fans['jihui'] < 1){
                    return_json(1,'您已经没有抽奖机会了');
                }
                //当前红包金额是否合法
                if ($amount < 0){
                    $amount = 0;
                }
                //金额大于0减机会加红包记录
                if($amount>0){
                    if (($amount/100)>$_C['redrain_once_amount']){
                        return_json(1,'获取红包失败');
                    }else{
                        $redrain_mode = $_S['redrain'];//1抵扣  2提现
                        if ($redrain_mode==1){
                            $amount = $amount/100;
                            //抵扣模式  计算金额
                        }elseif ($redrain_mode==2){
                            //提现模式   提交金额为红包数
                            $pct = ($amount/140)*$_C['redrain_once_amount'];
                            $amount = number_format($pct,2);
                        }else{
                            return_json(1,'获取红包失败');
                        }

                        //插入用户机会使用记录//减少用户抽奖机会
                        $res = RedRainModel::apiInsertChance($themeid,$_C,$fans,-1,$fromuid);
                        if ($res){
                            //用户日志收集
                            $log_msg = '获得红包'.$amount;
                            Userdata::addLog($themeid, $fans['uid'], 32, $log_msg);
                            $insert_user_redrain_flag = RedRainModel::insertUserRedRainItem($themeid,$fans,$_C,$amount,$res);
                        }
                    }
                }
                //获取当前用户的剩余机会
                $fans = RedRainModel::getFansInfoByWhere(['themeid'=>$themeid,'uid'=>$fans['uid']]);
                //获取机会的列表  判断对应的机会是否达到上限
                $method = RedRainModel::getUserMethod($_C,$_S,$themeid,$fans);
                //弹窗右侧按钮文字和类型
                if ($fans['jihui']>0){
                    $right_btn = ['type'=>'again','txt'=>'再玩一次'];
                }else{
                    $right_btn = ['type'=>'mine','txt'=>'我的红包'];
                }
                $format_res = [
                    'amount'=>$amount,
                    'remain_chance'=>$fans['jihui'],
                    'right_btn'=>$right_btn,
                    'method'=>$method
                ];
                return_json(0,'',$format_res);
            }
        }else{
            return_json(1,'非法请求');
        }
    }

    /**
     * Desc:用户提现
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/12 17:38
     */
    function verify()
    {
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        if ($fromtype!='wxapp') {
            return_json(1,'非法请求');
            exit();
        }
        $themeid = isset($_P['themeid'])?$_P['themeid']:'';
        $fromuid = isset($_P['fromuid'])?$_P['fromuid']:'';
        $workerid = isset($_P['workerid'])?$_P['workerid']:'';
        $theme = Theme::getThemeById($themeid);
        $fans = $this->checkuser();

        $error = '';
        //提现前的检测
        $redrain_error = RedPackValidate::redRain();
        if ($redrain_error['code'] && $redrain_error['msg']){
            $error = $redrain_error['msg'];
        }
        if ($error){
            return_json(1,$error,[]);
        }else{
            $f_id = $_P['f_id'];
            $from_fans = RedRainModel::getFansInfoByWhere(['themeid'=>$themeid,'uid'=>$fans['uid']]);
            //修改订单
            $res = RedRainModel::apiUseRedRainFlag($themeid,$from_fans,$f_id,$_S,$workerid);


            //基本检测
            $fans = $this->checkuser();
            //获我的最高可用的红包记录
            $my_redrain_base_info = RedRainModel::getUserCanUseRedRainFlag($themeid,$fans['uid'],$_C,$_S);
            //助力记录
            $my_friend_info = RedRainModel::getUserFriendInfo($themeid,$fans,$_C);
            //红包记录
            $my_redrain_flag =RedRainModel::getFrontUserRedRainList($themeid,$fans['uid'],$_C,$_S);
            //机会记录
            $my_chance_flag = RedRainModel::getFrontUserChanceList($themeid,$fans['uid']);
            $rules = $_C['redrain_rules'];
            //判断用户是否已经体现
            //$redrain_used = RedRainModel::getFlagTotal($fans['uid'],$themeid,1);
            //活动规则
            //员工信息
            if ($workerid && $workerid!='null'){
                $isworker = Worker::getThemeWorkerByUid($workerid,$themeid,1);
            }else{
                $isworker = Worker::getThemeWorkerByUid($fans['workerid'],$themeid,1);
            }
            $worker_info = [
                'name'=>$isworker['username'],
                'qrcode'=>$isworker['qrcode'],
                'avatar'=>$isworker['avatar'],
                'mobile'=>$isworker['mobile'],
            ];
            $company_mobile = $theme['mobile'];
            //用户日志收集
            Userdata::addLog($themeid, $fans['uid'], 28);
            $format_res = [
                'my_redrain_base_info'=>$my_redrain_base_info,
                'my_friend_info'=>$my_friend_info,
                'my_redrain_flag'=>$my_redrain_flag,
                'my_chance_flag'=>$my_chance_flag,
                'rules'=>$rules,
                // 'redrain_used'=>$redrain_used,
                'redrain_mode'=>$_S['redrain'],
                'redrain_get_type'=>$_C['redrain_get_type'],
                'worker_info'=>$worker_info,
                'company_mobile'=>$company_mobile,
            ];
            if (empty($res)){
                return_json(1, '该红包核销失败，请检查后重试',$format_res);
            }else{
                return_json(0, '核销成功',$format_res);
            }
        }
    }
}